package com.siyoumi.app.modules.app_ess.service;

import com.siyoumi.app.entity.EssModule;
import com.siyoumi.app.modules.app_ess.vo.EssModuleAudit;
import com.siyoumi.app.modules.app_ess.vo.VaEssModule;
import com.siyoumi.app.service.EssModuleService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.service.IWebService;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

//场景
@Slf4j
@Service
public class SvcEssModule
        implements IWebService {
    static public SvcEssModule getBean() {
        return XSpringContext.getBean(SvcEssModule.class);
    }

    static public EssModuleService getApp() {
        return EssModuleService.getBean();
    }


    public JoinWrapperPlus<EssModule> listQuery() {
        return listQuery(InputData.getIns());
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<EssModule> listQuery(InputData inputData) {
        String name = inputData.input("name");

        JoinWrapperPlus<EssModule> query = getApp().join();
        query.eq("emod_x_id", XHttpContext.getX());

        if (XStr.hasAnyText(name)) { //名称
            query.like("emod_name", name);
        }

        return query;
    }

    public XReturn edit(InputData inputData, VaEssModule vo) {
        List<String> ignoreField = new ArrayList<>();
        if (inputData.isAdminEdit()) {
            ignoreField.add("emod_acc_id");
        }

        return XApp.getTransaction().execute(status -> {
            XReturn r = getApp().saveEntity(inputData, vo, true, ignoreField);
            return r;
        });
    }

    /**
     * 删除
     */
    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        XReturn r = XReturn.getR(0);

        getApp().delete(ids);

        return r;
    }

    /**
     * 审核
     *
     * @param vo
     */
    @Transactional(rollbackFor = Exception.class)
    public XReturn audit(EssModuleAudit vo) {
        List<EssModule> list = getApp().get(vo.getIds());
        for (EssModule entity : list) {
            if (Objects.equals(entity.getEmod_enable(), vo.getEnable())) {
                continue;
            }

            EssModule entityUpdate = new EssModule();
            entityUpdate.setEmod_id(entity.getKey());
            entityUpdate.setEmod_enable(vo.getEnable());
            getApp().updateById(entityUpdate);
        }
        return EnumSys.OK.getR();
    }
}
